package com.minio.config;

import com.minio.property.MinioConfigurationProperties;
import com.minio.template.MinioTemplate;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;

/**
 * @ClassName: MinioConfig
 * @Description: minio配置类
 * @Author: xuweiLi
 * @Create: 2025/7/4 20:11
 **/
@AutoConfiguration
@ConditionalOnClass({MinioClient.class})
@ConditionalOnProperty(value = "minio.enable",havingValue = "true")
@EnableConfigurationProperties(MinioConfigurationProperties.class)
public class MinioAutoConfiguration {

    protected final Log logger = LogFactory.getLog(MinioAutoConfiguration.class);

    @Bean
    @ConditionalOnMissingBean(MinioClient.class)
    public MinioClient minioClient(MinioConfigurationProperties properties) throws Exception {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(properties.getEndpoint())
                .credentials(properties.getAccessKey(), properties.getSecretKey())
                .endpoint(properties.getEndpoint())
                .build();
        final String bucket = properties.getBucket();
        boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        logger.info("bucketExists: " + bucketExists);
        if (!bucketExists) {
            logger.info("Creating bucket " + bucket);
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            logger.info("Bucket " + bucket + " created");
            if (StringUtils.hasText(properties.getConfig())) {
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucket).config(properties.getConfig())
                        .build());
            }
            logger.info("Bucket " + bucket + " set policy successful!");
        } else {
            logger.info("Bucket " + bucket + " already exists");
        }
        return minioClient;
    }

    @Bean
    @ConditionalOnBean(MinioClient.class)
    public MinioTemplate minioTemplate(MinioClient minioClient, MinioConfigurationProperties properties) {
        MinioTemplate minioTemplate = new MinioTemplate();
        minioTemplate.setMinioClient(minioClient);
        minioTemplate.setProperties(properties);
        return minioTemplate;
    }

}